#!/usr/bin/perl

use strict;
use warnings;
use Smart::Comments;

use lib '../lib';

use POE qw(Component::Gearman);
use PoeHelper;

use Utils;

my @func = qw(reverse wc add);
my @event = qw(foo);

# 创建 POE 主 Session
spawnSession( @func, @event );

run POE::Kernel;
exit 0;

event _start {
    runlog( TA => 'TA 启动中...' );

    alias_set( 'mainSession' );

    spawn POE::Component::Gearman::Worker {
        Alias               => 'GearmanWorker',
        JobServers          => [ '127.0.0.1' ],
        ReconnectInterval   => 3,
        Prefix              => '',
    };

    delay foo => 10;
}

event foo {
    post GearmanWorker => register => @func;
}

service reverse {
    my $job = shift;

    my $data = $job->workload();

    foreach my $line ( split /\r?\n/, $data ){
        $line = reverse $line;
        $job->data( "$line\n" );
    }

    $job->complete();
}

service wc {
    my $job = shift;

    my $data = $job->workload();

    my $count = 0;
    foreach my $line ( split /\r?\n/, $data ){
        $count++;
    }

    $job->complete( "$count\n" );
}

service add {
    my $job = shift;

    my $data = $job->workload();

    my ($x, $y) = split /\s+/, $data;

    $job->complete( $x + $y );
}
